<?php

namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use App\Http\Requests\PermissionCreateRequest;
use App\Http\Requests\PermissionUpdateRequest;
use App\Http\Resources\PermissionResource;
use App\Models\Permission;
use Illuminate\Http\Request;

class PermissionController extends Controller
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new Permission();
    }

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $rows = $this->model->get()->sortByDesc('sort');
        return $this->success('get data list', PermissionResource::collection($rows));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param PermissionCreateRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(PermissionCreateRequest $request)
    {
        $data = $request->post();
        $row = $this->model::create($data);
        if (!$row) {
            return $this->failure('创建权限失败');
        }

        return $this->success('创建权限成功', PermissionResource::make($row));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param PermissionUpdateRequest $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(PermissionUpdateRequest $request, $id)
    {
        $permission = $this->model::find($id);
        if (empty($permission)) {
            $this->failure('该权限不存在');
        }
        $data = $request->all();
        $res = $permission->update($data);
        if ($res === false) {
            return $this->failure('更新权限失败');
        }
        return $this->success('更新权限成功', PermissionResource::make($permission));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int|string $ids
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($ids)
    {
        $ids = is_array($ids) ? $ids : func_get_args();
        if (empty($ids)) {
            return $this->failure('请选择删除项');
        }
        $res = $this->model::destroy($ids);
        if (!$res) {
            return $this->failure('删除权限失败');
        }
        return $this->success('删除权限成功');
    }
}
